﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using Sunboxsoft.Common;
using Sunboxsoft.ASMS.Client.UI.Properties;
namespace Sunboxsoft.ASMS.Client.UI.Create
{
    /// <summary>
    /// 创建充值单
    /// </summary>
    public partial class CreateRechargeBillView : UserControl, IView
    {
        #region fields
        Promise _promise = new Promise();
        /// <summary>
        /// 充值客户
        /// </summary>
        WebRef.VCustomer customer = null;
        WebRef.ECustomer newCustomer = null;
        private List<WebRef.ESalesPrice> _priceList;
        #endregion

        public CreateRechargeBillView()
        {
            InitializeComponent();
            ValidationManager.Register(this, new Common.Validations.SearchLookUpEditValidation(this.ctlLookUpRechargeItem, "充值项目"));
            ValidationManager.Register(this, new Common.Validations.SearchLookUpEditValidation(this.ctlLookUpSaleChannel, "销售渠道"));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(this.ctlEditMemo, "充值项目", true));
        }
        public CreateRechargeBillView(WebRef.VCustomer customer)
            : this()
        {
            this.customer = customer;
            this.ctlEditCustomer.Text = customer.Name;
        }
        public CreateRechargeBillView(WebRef.ECustomer newCustomer)
            : this()
        {
            this.newCustomer = newCustomer;
            this.ctlEditCustomer.Text = newCustomer.Name;
        }


        #region IView 成员
        public void RegisterAction(ActionNodeCollection collection)
        {
            collection.AddAction(new ActionNode("save", Resources.isOK, "保存", btnSave_Click))
                .AddAction(new ActionNode("submitAndChecked", Resources.isSettling, "保存并收银", btnSaveAndChecked_Click))
                .AddAction(new ActionNode("cancel", Resources.isBack, "取消", btnCancel_Click));
        }

        public void Active(ViewActiveArgs args)
        {
            _promise.Then(() =>
            {
                ctlLookUpSaleChannel.BindEMasterDataItem(_promise, Domain.Constant.MasterDataCodes.SalesChannel, null, null, false, true);
            })
                .Then(() =>
            {
                ctlLookUpSalesManager.BindVStaffPosition(_promise, Domain.Constant.StaffPosts.SalesManager);
            }).Then(() =>
            {
                ctlLookUpRechargeItem.BindERechargeItem(_promise);
            })
            .Run();
        }

        public void Resume(ViewResumeArgs args)
        {
            if (args.ClosedArgs != null && args.ClosedArgs.Result)
            {
                if (args.ClosedArgs.View is Pickers.VCustomerAccuratelyPicker)
                {
                    newCustomer = null;
                    customer = args.ClosedArgs.Data as WebRef.VCustomer;
                    ctlEditCustomer.Tag = customer;
                    ctlEditCustomer.Text = customer.Name;
                }
            }
        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("客户充值");
        }
        #endregion

        #region Method
        /// <summary>
        /// 数据检查
        /// </summary>
        /// <returns></returns>
        private bool ValidateData()
        {
            if (newCustomer == null)
            {
                if (customer == null)
                {
                    UIContext.Current.ViewManager.ShowWarning("请选择客户！");
                    return false;
                }
            }
            string message = null;
            if (!ValidationManager.Validate(this, out message))
            {
                UIContext.Current.ViewManager.ShowError(message);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 获取充值项目
        /// </summary>
        private WebRef.ERechargeItem GetSelectRechargeItem()
        {
            WebRef.ERechargeItem item = this.ctlLookUpRechargeItem.EditValue as WebRef.ERechargeItem;
            return item;
        }
        /// <summary>
        /// 创建充值单
        /// </summary>
        private void CreateRechargeBill(string flag)
        {
            WebRef.EMasterDataItem selectedChannel = this.ctlLookUpSaleChannel.GetSelectedValue<WebRef.EMasterDataItem>();
            if (selectedChannel == null)
            {
                _promise.Reject();
                return;
            }

            WebRef.ERechargeBill bill = new WebRef.ERechargeBill();
            bill.BusinessId = ModuleContext.Current.BusinessId.Value;
            bill.StationId = ModuleContext.Current.StationId.Value;
            if (this.customer != null)
            {
                bill.CustomerId = this.customer.Id;
            }
            if (this.newCustomer != null)
            {
                bill.CustomerId = this.newCustomer.Id;
            }
            bill.RechargeItemId = GetSelectRechargeItem().Id;
            bill.RechargeChannel = Domain.Constant.RechargeChannels.RechargeItem;
            bill.BoughtChannel = selectedChannel.Code;
            bill.Memo = ctlEditMemo.Text.Trim();
            bill.SalesManagerId = ctlLookUpSalesManager.GetSelectedValue<WebRef.VStaffPosition>().GetStaffId();

            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                SingleResult<Guid> result = new Service.CreateService().CreateRechargeBill(bill);
                this.BeginInvoke(new Action(() =>
                {
                    this.HideMask();
                    if (result.IsSuccess)
                    {
                        if (flag.Equals(""))
                        {
                            UIContext.Current.ViewManager.CloseView(true, null);
                        }
                        else
                        {
                            UIContext.Current.ViewManager.ReplaceView(new Recharge.CheckedOutRechargeBillView(result.Data));
                        }
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
        }

        /// <summary>
        /// 显示销售价格
        /// </summary>
        private void UpdatePriceLabel(WebRef.ERechargeItem item, WebRef.EMasterDataItem selectedChannel)
        {
            if (item != null && selectedChannel != null && _priceList != null)
            {
                for (int index = 0; index < _priceList.Count; index++)
                {
                    if (_priceList[index].Channel == selectedChannel.Code)
                    {
                        this.txtYSAmount.EditValue = _priceList[index].Price;
                        this.txtCRAmount.EditValue = item.Amount;
                        this.txtSalesCom.EditValue = Domain.Calculation.CalcUtil.CalcCommissionAmount(_priceList[index].Price, item.SalesCommissionType, item.SalesCommission);
                        return;
                    }
                }
            }

            this.txtYSAmount.EditValue = null;
            this.txtCRAmount.EditValue = null;
            this.txtSalesCom.EditValue = null;
        }
        #endregion

        #region actions
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnSave_Click(object sender, object e)
        {
            if (ValidateData())
            {
                CreateRechargeBill("");
            }
        }
        void btnSaveAndChecked_Click(object sender, object e)
        {
            if (ValidateData())
            {
                CreateRechargeBill("Checked");
            }
        }
        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnCancel_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.CloseView(false, null);
        }
        /// <summary>
        /// 获取充值客户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlEditCustomer_Click(object sender, EventArgs e)
        {
            UIContext.Current.ViewManager.PopupView(new Pickers.VCustomerAccuratelyPicker(), new PopupViewArgs("选择客户") );
        }
        /// <summary>
        /// 根据选择的充值项目获取应收金额/充入金额
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlLookUpRechargeItem_EditValueChanged(object sender, EventArgs e)
        {
            WebRef.ERechargeItem item = GetSelectRechargeItem();
            if (item != null)
            {
                // 获取销售价格
                this.ShowMask();
                UIContext.Current.InvokeAsync(() =>
                {
                    ListResult<WebRef.ESalesPrice> result = new Service.QueryService().QuerySalePriceList(item.Id, Domain.Constant.SalePriceTargetTypes.RechargeItem);
                    this.BeginInvoke(new Action(() =>
                    {
                        if (result.IsSuccess)
                        {
                            _priceList = result.Data.Items;
                            UpdatePriceLabel(item, ctlLookUpSaleChannel.GetSelectedValue<WebRef.EMasterDataItem>());

                            _promise.Resolve();
                        }
                        else
                        {
                            _priceList = null;
                            UpdatePriceLabel(item, ctlLookUpSaleChannel.GetSelectedValue<WebRef.EMasterDataItem>());

                            UIContext.Current.ViewManager.ShowError(result.Message);
                            _promise.Reject();
                        }
                        this.HideMask();
                    }));
                });
            }
        }

        private void ctlLookUpSaleChannel_EditValueChanged(object sender, EventArgs e)
        {
            UpdatePriceLabel(GetSelectRechargeItem(), ctlLookUpSaleChannel.GetSelectedValue<WebRef.EMasterDataItem>());
        }
        #endregion
    }
}
